package com.weilai.controller.Interceptor;

import com.weilai.domain.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器类
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final String LOGIN_PAGE = "/login";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            // 用户已经登录，可以访问任意界面，放行
            return true;
        }

        try {
            // 用户未登录，重定向到登录页面
            // 将提示信息存入Session（登录页面显示后需立即清除）
            request.getSession().setAttribute("loginError", "请先登录");
            response.sendRedirect(LOGIN_PAGE);
        } catch (Exception e) {
            // 处理重定向异常，记录日志或进行其他操作
            System.err.println("重定向异常: " + e.getMessage());
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理后的逻辑
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后的逻辑
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}